﻿using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Windows.Forms;
using System.IO;

using SourceGrid;
using iPdf.Properties;

namespace iPdf
{
    class FilePathEditor : SourceGrid.Cells.Editors.TextBoxButton
    {
        private bool hasEntered;   //flag to prevent multiple entering during one session
        private string extension = string.Empty;

        public string Extension
        {
            get
            {
                return extension;
            }
            set
            {
                extension = value;
            }
        }

        public FilePathEditor(string ext)
            : base(typeof(string))
        {
            extension = string.IsNullOrEmpty(ext)? Global.PdfExt : ext;

            hasEntered = false;

            this.EditableMode = EditableMode.DoubleClick | EditableMode.F2Key;
            Control.DialogOpen += new EventHandler(Control_DialogOpen);
            Control.Validating += new CancelEventHandler(Control_Validating);
            Control.Validated += new EventHandler(Control_Validated);
            Control.TextBox.TextChanged += new EventHandler(TextBox_TextChanged);
            Control.Enter += new EventHandler(Control_Enter);
            Control.Leave += new EventHandler(Control_Leave);

            UseCellViewProperties = false;
        }

        private void Control_Enter(object o, EventArgs e)
        {
            if (hasEntered == true)
            {
                return;
            }
            hasEntered = true;

            //disable ribbon
            Global.MainWindow.EnableRibbon(false);

            //set the current directory
            DevAge.Windows.Forms.DevAgeTextBoxButton sender =
                    (DevAge.Windows.Forms.DevAgeTextBoxButton)o;
            string fileName = sender.TextBox.Text;

            if (string.IsNullOrEmpty(fileName) == false)
            {
                try
                {
                    FileInfo info = new FileInfo(fileName);
                    if (string.IsNullOrEmpty(info.DirectoryName) == false &&
                        info.Directory != null && info.Directory.Exists)
                    {
                        Directory.SetCurrentDirectory(new FileInfo(fileName).DirectoryName);
                    }
                }
                catch
                {
                    //ignore the exception
                }
            }

            sender.TextBox.Text = Helper.RemoveFileExt(fileName);
        }
        
        private static void RegularizeExtension(ref string fileName, string extension)
        {
           if (!fileName.EndsWith(extension, StringComparison.OrdinalIgnoreCase))
            {
                fileName += extension;
            }
        }

        private void Control_Leave(object o, EventArgs e)
        {
            //set the current directory
            DevAge.Windows.Forms.DevAgeTextBoxButton sender =
                    (DevAge.Windows.Forms.DevAgeTextBoxButton)o;
            string fileName = sender.TextBox.Text;
            RegularizeExtension(ref fileName, extension);

            if (IsValidFilePath(fileName))
            {
                sender.TextBox.Text = fileName;
                hasEntered = false;
            }
            else
            {
                sender.Focus();
            }
        }

        private void Control_DialogOpen(object sender, EventArgs e)
        {
            using (SaveFileDialog saveDlg =
                Helper.CreateSaveFileDialog(FileFormat.PdfFormat, (string)Control.Value))
            {
                if (saveDlg.ShowDialog(EditCellContext.Grid) == DialogResult.OK)
                {
                    SetEditValue(Helper.RemoveFileExt(saveDlg.FileName));
                }
            }
        }

        private bool IsValidFilePath(string fileName)
        {
            if (string.IsNullOrEmpty(fileName) ||
                Helper.RemoveFileExt(fileName) == string.Empty )
            {
                return false;
            }

            string srcFileName = (string) Global.Grid.Source.GetValueAt(this.EditCellContext.Position.Row);
            if (srcFileName.Equals( fileName, StringComparison.OrdinalIgnoreCase))
            {
                return false;
            }

            try
            {
                FileInfo info = new FileInfo(fileName);
                if (info == null || info.Directory == null)
                {
                    return false;
                }
                if (!info.Directory.Exists)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }

        private void TextBox_TextChanged(object sender, EventArgs e)
        {
            DevAge.Windows.Forms.DevAgeTextBox textBox =
                                    (DevAge.Windows.Forms.DevAgeTextBox)sender;
            string fileName = textBox.Text;

            RegularizeExtension(ref fileName, extension);

            if (!IsValidFilePath(fileName))
            {
                textBox.ShowBalloon(Resources.BadFilePath, Resources.Error,
                                    PocketNerd.Windows.Forms.BalloonIcon.Exclamation);
            }
        }

        private void Control_Validating(object sender, CancelEventArgs e)
        {
            DevAge.Windows.Forms.DevAgeTextBoxButton textBoxButton =
                (DevAge.Windows.Forms.DevAgeTextBoxButton)sender;
            string fileName = textBoxButton.TextBox.Text;

            RegularizeExtension(ref fileName, extension);

            if (!IsValidFilePath(fileName))
            {
                e.Cancel = true;
            }
            else
            {
                FileInfo file = new FileInfo(fileName);
                textBoxButton.TextBox.Text = file.FullName;
                //update the hasEntered flag
                hasEntered = false;
            }
        }

        private void Control_Validated(object sender, EventArgs e)
        {
            Global.MainWindow.EnableRibbon(true);
        }
    }

}
